package com.auditlog.converter;

import cn.hutool.core.lang.Assert;
import com.auditlog.converter.impl.*;
import com.auditlog.util.EnvUtils;

import java.sql.SQLException;
import java.util.LinkedList;

public class ConverterRegistry {

    private LinkedList<Converter> converters = new LinkedList<>();

    private ConverterRegistry() {
        register(new BlobConverter());
        register(new ByteArrayConverter());
        register(new ClobConverter());
        register(new SqlDateConverter());
        register(new SqlTimeConverter());
        register(new TimeStampConverter());
        register(new LocalDateTimeConverter());
        if (EnvUtils.isOracleDb()) {
            register(new OracleTimeStampConverter());
        }
    }

    private static class SingletonHolder {
        private static final ConverterRegistry INSTANCE = new ConverterRegistry();
    }

    public static ConverterRegistry getInstance() {
        return ConverterRegistry.SingletonHolder.INSTANCE;
    }

    public void register(Converter converter) {
        Assert.notNull(converter, "对象不能为空");
        converters.addFirst(converter);
    }

    public Converter getConverter(Class clazz) {
        return converters.stream().filter(converter -> converter.support(clazz)).findFirst()
                .orElse(new DefaultConverter());
    }

    public String convert2Str(Object object) throws SQLException {
        if (object == null) {
            return null;
        }
        Converter converter = this.getConverter(object.getClass());
        return converter.convert2Str(object);
    }
}
